package com.shop.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.shop.common.constant.RedisConstant;
import com.shop.common.entity.CommonResult;
import com.shop.common.pojo.User;
import com.shop.common.util.StrUtils;
import com.shop.server.mapper.UserMapper;
import com.shop.server.service.LoginService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author ghy
 * @version 1.0
 * @date 2020-10-30
 */
@Service
@Transactional
public class LoginServiceImpl implements LoginService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 登录
     *
     * @param map
     * {
     *     "uname":zhangsan,
     *     "password":"123456"
     * }
     * @return
     */
    @Override
    public CommonResult<User> login(Map map) {
        User loginUser = null;
        String pwd = (String) map.get("password");
        String uname = (String) map.get("uname");

        uname = uname.trim();

        if(uname.contains("@")){
            //邮箱

        }
        try {
            long phoneNum = Long.parseLong(uname);
            //手机
            loginUser = userMapper.findByPhone(uname);
            if(loginUser == null) {
                return null;
            }
            //判断密码
            if (passwordEncoder.matches(pwd,loginUser.getPassword())) {
                loginUser.setPassword("");
                //把用户信息存入到 redis
                String uuidToken = StrUtils.uuidToken();
                String loginToken = StrUtils.getRedisKey(RedisConstant.LOGIN_TOKEN, uuidToken);
                //把user变成json
                String jsonUser = JSON.toJSONString(loginUser);
                //将用户信息存入redis，7天有效
                stringRedisTemplate.opsForValue().set(loginToken, jsonUser, 7, TimeUnit.DAYS);
                //login_token_uuid="{用户信息json}"
                return new CommonResult<>(true, uuidToken, loginUser);
            }

        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        //用户名

        return null;
    }

    /**
     * 获取登录信息
     *  如果成功：返回一个CommonResult，data中封装的是一个map,包含用户信息
     *  如果失败：返回一个CommonResult，data中封装的就是一个失败消息:"网络繁忙，请刷新下页面"
     *
     * @param token
     * @return
     */
    @Override
    public CommonResult loginName(String token) {

        if(StringUtils.isBlank(token)) {
            return new CommonResult(false, "token为空", "网络繁忙，请刷新下页面");
        }

        //从redis去获取用户信息
        ////login_token_uuid="{用户信息json}"
        String redis_login_token = StrUtils.getRedisKey(RedisConstant.LOGIN_TOKEN, token);

        String userJson = stringRedisTemplate.opsForValue().get(redis_login_token);
        User user = JSON.parseObject(userJson, User.class);

        Map<String, String> map = new HashMap<>();
        map.put("id", user.getId().toString());
        map.put("username", user.getUsername());
        map.put("phone", user.getPhone());
        map.put("email", user.getEmail());
        return new CommonResult("成功获取到用户信息", map);
    }
}
